package com.quanyan.authority.filter;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.authority.cache.AuthorityRedisTemplate;
import com.quanyan.authority.constants.AuthorityConstants;
import com.quanyan.authority.model.db.TbAdminUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @Author Hugo.Wwg
 * @Since 2016-06-02
 */
@Component
public class CommonFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(CommonFilter.class);

    private static final String ADMIN_USER_TOKEN = "adminUserToken";

    @Autowired
    private AuthorityRedisTemplate authorityRedisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    private void ajaxError(ApiResponseEnum apiResponseEnum, ServletResponse response)
            throws IOException {
        response.getWriter().write(JSON.toJSON(APIResponse.returnFail(apiResponseEnum)).toString());
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String uri = request.getRequestURI();
        String userToken = request.getHeader(ADMIN_USER_TOKEN);
        logger.info("{}",uri);
        if (!uri.endsWith("login")){
            if(userToken != null && !"".equals(userToken)){
                TbAdminUser tbAdminUser = (TbAdminUser)authorityRedisTemplate.get(AuthorityConstants.ADMIN_USER_REDIS_KEY + userToken);
                if(tbAdminUser == null){
                    ajaxError(ApiResponseEnum.NEED_USER_LOGIN, response);
                    return;
                }
                req.setAttribute("adminUid", userToken);
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

}
